package com.qyhl.shop.shop.rush;

import android.text.style.TextAppearanceSpan;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.shop.R;
import com.qyhl.shop.R2;
import com.qyhl.shop.view.SaleProgressView;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.SpanUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.shop.ShopRushListBean;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 限时抢购
 */
@Route(path = ARouterPathConstant.SHOP_RUSH_PURCHASE_LIST)
public class ShopRushPurchaseActivity extends BaseActivity implements ShopRushPurchaseContract.ShopRushPurchaseView {
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    @Autowired(name = "shopId")
    int shopId;

    private int page = 1;

    private ShopRushPurchasePresenter mPresenter;

    private CommonAdapter<ShopRushListBean> commonAdapter;
    private List<ShopRushListBean> mDataList = new ArrayList<>();

    @Override
    protected int getContentView() {
        return R.layout.shop_activity_rush_purchase_list;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.fullScreen(true).statusBarDarkFont(false).init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        BusFactory.getBus().register(this);
        loadMask.setStatus(LoadingLayout.Loading);
        mPresenter = new ShopRushPurchasePresenter(this);

        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableRefresh(true);
        refresh.setEnableLoadMore(true);

        recycleView.setLayoutManager(new LinearLayoutManager(this));
        recycleView.setAdapter(commonAdapter = new CommonAdapter<ShopRushListBean>(this, R.layout.shop_item_rush_purchase_list, mDataList) {
            @Override
            protected void convert(ViewHolder holder, ShopRushListBean bean, int position) {
                RoundedImageView cover = holder.getView(R.id.cover);
                Glide.with(ShopRushPurchaseActivity.this)
                        .load(bean.getCoverPicUrl())
                        .apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                        .into(cover);

                holder.setText(R.id.title, bean.getName());

                TextView price = holder.getView(R.id.price);
                SpanUtils spanUtils = new SpanUtils(ShopRushPurchaseActivity.this);
                if (bean.getPrice() == 0) {
                    spanUtils.append("免费").setSpans(new TextAppearanceSpan(ShopRushPurchaseActivity.this, R.style.shop_gift_price_one));
                } else {
                    spanUtils.append("¥").setSpans(new TextAppearanceSpan(ShopRushPurchaseActivity.this, R.style.shop_gift_price_three))
                            .append(bean.getPrice() + "").setSpans(new TextAppearanceSpan(ShopRushPurchaseActivity.this, R.style.shop_gift_price_two));
                }

                price.setText(spanUtils.create());

                SaleProgressView saleProgressView = holder.getView(R.id.spv);
                saleProgressView.setVisibility(View.VISIBLE);
                saleProgressView.setTotalAndCurrentCount(100, bean.getReceivePercent(), bean.getReceiveStatus());

                TextView rushPurchaseBtn = holder.getView(R.id.rush_purchase_btn);
                if (bean.isReceived()) {
                    if (bean.isPay()) {
                        rushPurchaseBtn.setEnabled(false);
                        rushPurchaseBtn.setText("已抢购");
                    } else {
                        rushPurchaseBtn.setEnabled(true);
                        rushPurchaseBtn.setText("待支付");
                    }

                    if (bean.getReceiveStatus() == 5) {
                        saleProgressView.setVisibility(View.GONE);
                    }
                } else {
                    if (bean.getReceiveStatus() == 4) {
                        rushPurchaseBtn.setEnabled(false);
                        rushPurchaseBtn.setText("已售罄");
                    } else if (bean.getReceiveStatus() == 5) {
                        rushPurchaseBtn.setEnabled(false);
                        rushPurchaseBtn.setText("已结束");
                        saleProgressView.setVisibility(View.GONE);
                    } else {
                        rushPurchaseBtn.setEnabled(true);
                        rushPurchaseBtn.setText("立即抢");
                    }
                }

                rushPurchaseBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (bean.isReceived() && !bean.isPay()) {
                            ARouter.getInstance()
                                    .build(ARouterPathConstant.SHOP_GIFT_ORDER)
                                    .withInt("id", bean.getUserGiftId())
                                    .navigation();
                        } else {
                            ARouter.getInstance()
                                    .build(ARouterPathConstant.SHOP_RUSH_PURCHASE_DETAIL)
                                    .withInt("id", bean.getId())
                                    .navigation();
                        }
                    }
                });

            }
        });

        if (shopId == 0) {
            mPresenter.getListBySite(page);
        } else {
            mPresenter.getListByShop(shopId, page);
        }


    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                page = 1;
                if (shopId == 0) {
                    mPresenter.getListBySite(page);
                } else {
                    mPresenter.getListByShop(shopId, page);
                }
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                if (shopId == 0) {
                    mPresenter.getListBySite(page);
                } else {
                    mPresenter.getListByShop(shopId, page);
                }
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (shopId == 0) {
                    mPresenter.getListBySite(page);
                } else {
                    mPresenter.getListByShop(shopId, page);
                }
            }
        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                ARouter.getInstance()
                        .build(ARouterPathConstant.SHOP_RUSH_PURCHASE_DETAIL)
                        .withInt("id", mDataList.get(i).getId())
                        .navigation();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });

    }

    @Override
    public void setList(List<ShopRushListBean> beanList) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        if (beanList == null) {
            setError("暂无任何内容!");
            return;
        }
        if (page != 1) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            mDataList.clear();
        }
        page++;
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setError(String msg) {
        if (page != 1) {
            refresh.finishLoadMore();
            if (!NetUtil.isNetworkAvalible(this)) {
                showToast("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {

            } else {
                showToast(msg);
            }
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setReloadButtonText("点击重试~");
            if (!NetUtil.isNetworkAvalible(this)) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(Event.GiftRefresh event) {
        if (event != null) {
            for (int i = 0; i < mDataList.size(); i++) {
                if (mDataList.get(i).getId() == event.getGiftId()) {
                    if (event.getStatus() == 4) {
                        mDataList.get(i).setReceiveStatus(4);
                    } else {
                        mDataList.get(i).setReceiveCount(mDataList.get(i).getQuantity() - event.getRestNum());
                        mDataList.get(i).setReceived(true);
                        mDataList.get(i).setPay(true);

                    }
                    commonAdapter.notifyItemChanged(i);
                }
            }
        }
    }

    @OnClick(R2.id.back_btn)
    public void onClick() {
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void doRefresh(Event.OrderRefresh event) {
        if (event != null) {
            page = 1;
            if (shopId == 0) {
                mPresenter.getListBySite(page);
            } else {
                mPresenter.getListByShop(shopId, page);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
    }
}
